﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace Basefr.Runtime.Helpers
{
    public static class HttpHelper
    {
        public static async Task<string> GetAsync(string url, Dictionary<string, string> headers = null, int timeout = 0)
        {
            using (var client = new HttpClient())
            {
                if (headers != null && headers.Any())
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, 0, timeout);
                }

                var result = await client.GetStringAsync(url);

                return result;
            }
        }

        public static string Get(string url, Dictionary<string, string> headers = null, int timeout = 0)
        {
            return GetAsync(url, headers, timeout).Result;
        }

        public static async Task<string> PostAsync(string url, string postData, Dictionary<string, string> headers = null, string contentType = "application/json", int timeout = 0, Encoding encoding = null)
        {
            using (var client = new HttpClient())
            {
                if (headers != null && headers.Any())
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                if (timeout > 0)
                {
                    client.Timeout = new TimeSpan(0, 0, 0, timeout);
                }

                using (var content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                {
                    if (!string.IsNullOrWhiteSpace(contentType))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                    }

                    using (var response = await client.PostAsync(url, content))
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        return result;
                    }
                }
            }
        }

        public static string Post(string url, string postData, Dictionary<string, string> headers = null, string contentType = "application/json", int timeout = 0, Encoding encoding = null)
        {
            return PostAsync(url, postData, headers, contentType, timeout, encoding).Result;
        }
    }
}
